package cn.com.czpb.client.module.news.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.text.Selection;
import android.text.Spannable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.custorm.CircleImageView;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.model.usercenter.EmptyEntity;
import cn.com.czpb.client.module.news.activity.CommentNewActivity;
import cn.com.czpb.client.module.news.dialog.CommPop;
import cn.com.czpb.client.module.personal.acticity.PersonPageActivity;
import cn.com.czpb.client.module.subscribe.activity.SubscribeDetailActivity2;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.AAnim;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.SinglePicker;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/14.
 */

public class NewsCommentExpandAdapter extends BaseExpandableListAdapter {
    private List<CommBean> list_parent;
    private Map<String, List<CommBean.ChildrenEntity>> list_child;
    private Context context;
    private SPUtil spu;
    private String nid, type;

    public NewsCommentExpandAdapter(List<CommBean> list_parent,
                                    Map<String, List<CommBean.ChildrenEntity>> list_child,
                                    Context context
            , String nid, String type, onViewClick onViewClick) {
        this.list_parent = list_parent;
        this.list_child = list_child;
        this.context = context;
        spu = SPUtil.getInstance();
        this.nid = nid;
        this.type = type;
        this.onViewClick = onViewClick;
    }

    @Override
    public int getGroupCount() {
        return list_parent.size();
    }

    @Override
    public int getChildrenCount(int i) {
        try {
            String cid = list_parent.get(i).getCid();
            return list_child.get(cid).size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Object getGroup(int i) {
        return list_parent.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        List<CommBean.ChildrenEntity> childs = list_child.get(list_parent.get(i).getCid());
        if (childs != null) {
            return childs.get(i1);
        }
        return null;
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public int getGroupTypeCount() {
        return 1;
    }

    @Override
    public int getChildTypeCount() {
        return 1;
    }

    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
        final ParentViewHolder holder;
        if (view == null) {
            view = View.inflate(context, R.layout.common_parent, null);
            holder = new ParentViewHolder();
            holder.iv_touxiang = view.findViewById(R.id.iv_user_comm);
            holder.iv_dianzan = view.findViewById(R.id.iv_dianzan);
            holder.tv_name = view.findViewById(R.id.tv_name_comm);
            holder.tv_dianzan = view.findViewById(R.id.tv_dianzan_comm);
            holder.tv_time = view.findViewById(R.id.tv_time_comm);
            holder.tv_content = view.findViewById(R.id.tv_content_comm);
            holder.tv_reply = view.findViewById(R.id.tv_reply_comm);
            holder.tv_lv = view.findViewById(R.id.tv_lv_comm);
            holder.ll_dianzan = view.findViewById(R.id.ll_dianzan);
            holder.ll_user = view.findViewById(R.id.ll_user);
            holder.ll_reply = view.findViewById(R.id.ll_reply);
            holder.vip = view.findViewById(R.id.vip);
            view.setTag(holder);
        } else {
            holder = (ParentViewHolder) view.getTag();
        }
        final CommBean obj = list_parent.get(i);
        holder.ll_dianzan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Priase(null, obj, 0, holder.tv_dianzan, holder.iv_dianzan);
                obj.setPraise("");
            }
        });
//        holder.tv_reply.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ReplyDialog dialog = new ReplyDialog(context, R.style.ChangeNamedialog, obj.getCid(), obj.getNickname());
//                dialog.show();
//            }
//        });
        holder.ll_reply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onViewClick.OnClicker(i);
            }
        });
        holder.ll_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                if ("1".equals(obj.getMediatype())) {
                    intent.putExtra("focusUid", obj.getUid());
                    intent.setClass(context, SubscribeDetailActivity2.class);
                } else {
                    intent.putExtra("uid", obj.getUid());
                    intent.setClass(context, PersonPageActivity.class);
                }
                context.startActivity(intent);
                AAnim.ActivityStartAnimation((Activity) context);
            }
        });
        holder.tv_content.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                holder.tv_content.setBackgroundColor(context.getResources().getColor(R.color.color_d4d4d4));
                final String msg = holder.tv_content.getText().toString();
                CommPop cp = new CommPop((Activity) context, holder.tv_content, new CommPop.OnClickListeners() {
                    @Override
                    public void OnClicked(View view) {
                        switch (view.getId()) {
                            case R.id.tv_copy:
                                ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                cmb.setText(msg);
                                TUtils.toast("已复制");

                                break;
                            case R.id.tv_report:
//                                        ClipboardManager cmb1 = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
//                                        cmb1.setText(msg);
                                SinglePicker picker = ShowReport();
                                picker.setOnItemPickListener(new OnItemPickListener<String>() {
                                    @Override
                                    public void onItemPicked(int index, String item1) {
                                        ReportUser(obj.getUid(), msg, index + "");

                                    }
                                });
                                picker.show();
                                break;
                        }
                    }
                });
                cp.showAsPullUp(holder.tv_content, 0, 0);

                return true;
            }

        });

        try {
            Glide.with(context).load(obj.getAvatar_path()).into(holder.iv_touxiang);
            holder.tv_name.setText(TextUtils.getLengthText(obj.getNickname(), 8));
            holder.tv_lv.setText(obj.getUlevel());
            holder.tv_dianzan.setText(obj.getPraise());
            holder.tv_content.setText(obj.getContent());
            holder.tv_time.setText(obj.getDateline());
            if ("1".equals(obj.getMediatype())) {
                holder.vip.setVisibility(View.VISIBLE);
            }
            if (obj.getIspraise().equals("0")) {
                holder.tv_dianzan.setTextColor(context.getResources().getColor(R.color.color_999999));
                holder.iv_dianzan.setImageResource(R.drawable.dianzan);
            } else {
                holder.tv_dianzan.setTextColor(context.getResources().getColor(R.color.color_df3031));
                holder.iv_dianzan.setImageResource(R.drawable.dianzan_selected);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        return view;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        final ChildViewHolder holder;
        if (view == null) {
            view = View.inflate(context, R.layout.item_comm_recycler, null);
            holder = new ChildViewHolder();
            holder.iv_dianzan = view.findViewById(R.id.iv_dianzan);
            holder.tv_name = view.findViewById(R.id.tv_name_comm_recycler);
            holder.tv_dianzan = view.findViewById(R.id.tv_dianzan_comm);
            holder.tv_time = view.findViewById(R.id.tv_time_comm_recycler);
            holder.tv_lv = view.findViewById(R.id.tv_lv_comm_recycler);
            holder.tv_content = view.findViewById(R.id.tv_content_comm_recycler);
            holder.ll_dianzan = view.findViewById(R.id.ll_dianzan);
            holder.ll_user = view.findViewById(R.id.ll_user);
            holder.vip = view.findViewById(R.id.vip);
            view.setTag(holder);
        } else {
            holder = (ChildViewHolder) view.getTag();
        }
        final CommBean.ChildrenEntity obj = (CommBean.ChildrenEntity) getChild(i, i1);
        if ("1".equals(obj.getMediatype())) {
            holder.vip.setVisibility(View.VISIBLE);
        }
        holder.tv_name.setText(TextUtils.getLengthText(obj.getNickname(), 8));
        holder.tv_dianzan.setText(obj.getPraise());
        holder.tv_content.setText(obj.getContent());
        holder.tv_time.setText(obj.getDateline());
        holder.tv_content.setText(obj.getContent());
        if (obj.getIspraise().equals("0")) {
            holder.tv_dianzan.setTextColor(context.getResources().getColor(R.color.color_999999));
            holder.iv_dianzan.setImageResource(R.drawable.dianzan);
        } else {
            holder.tv_dianzan.setTextColor(context.getResources().getColor(R.color.color_df3031));
            holder.iv_dianzan.setImageResource(R.drawable.dianzan_selected);
        }
        holder.ll_dianzan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (spu.getUser() != null) {
                Priase(obj, null, 1, holder.tv_dianzan, holder.iv_dianzan);

//                } else {
//                    Intent intent = new Intent(context, LoginActivity.class);
//                    context.startActivity(intent);
//                    TUtils.toast("请先登录");
//
//                }

            }
        });
        holder.ll_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                if ("1".equals(obj.getMediatype())) {
                    intent.putExtra("focusUid", obj.getUid());
                    intent.setClass(context, SubscribeDetailActivity2.class);
                } else {
                    intent.putExtra("uid", obj.getUid());
                    intent.setClass(context, PersonPageActivity.class);
                }
                context.startActivity(intent);
                AAnim.ActivityStartAnimation((Activity) context);
            }
        });
//        holder.tv_content.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ReplyDialog dialog = new ReplyDialog(context, R.style.ChangeNamedialog, obj.getCid(), obj.getNickname());
//                dialog.show();
//            }
//        });

        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }


    public interface onViewClick {
        void OnClicker(int pisotion);
    }

    private onViewClick onViewClick;


    class ParentViewHolder {
        CircleImageView iv_touxiang;
        TextView tv_name;
        TextView tv_lv;
        TextView tv_content;
        TextView tv_time;
        TextView tv_reply;
        LinearLayout ll_user;
        LinearLayout ll_dianzan;
        LinearLayout ll_reply;
        ImageView iv_dianzan;
        TextView tv_dianzan;
        ImageView vip;
    }

    class ChildViewHolder {
        CircleImageView iv_touxiang;
        TextView tv_name;
        TextView tv_lv;
        TextView tv_content;
        TextView tv_time;
        TextView tv_reply;
        LinearLayout ll_user;
        LinearLayout ll_dianzan;
        ImageView iv_dianzan;
        TextView tv_dianzan;
        ImageView vip;
    }


    public void Priase(final CommBean.ChildrenEntity cid, final CommBean obj, final int type, final TextView tv, final ImageView iv) {

        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(context));
        if (type == 0) {
            map.put("cid", obj.getCid());
        } else if (type == 1) {
            map.put("cid", cid.getCid());
        }
        map.put("siteid", InterfaceJsonfile.SITEID);

        Factory.provideHttpService().PraiseOnComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity emptyEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity emptyEntity) {

                        LogUtils.e("code---" + emptyEntity.code);
                        if (emptyEntity.code.equals("200")) {
                            tv.setText(emptyEntity.data.getPraisenum());
                            if (type == 1) {
                                cid.setPraise(emptyEntity.data.getPraisenum());
                                cid.setIspraise("1");
                            }else if (type==0){
                                obj.setPraise(emptyEntity.data.getPraisenum());
                                obj.setIspraise("1");
                            }
                            tv.setTextColor(context.getResources().getColor(R.color.color_df3031));
                            iv.setImageResource(R.drawable.dianzan_selected);
                            Intent intent = new Intent();
                            intent.setAction(CommentNewActivity.PRAISE);
                            context.sendBroadcast(intent);
//                            notifyDataSetChanged();
                        } else {
                            TUtils.toast(emptyEntity.msg);
                        }
                    }
                });

    }

    class ReplyDialog extends Dialog implements View.OnClickListener {
        EditText et_reply;
        TextView tv_send;
        String cid;
        String nicName;

        public ReplyDialog(Context context) {
            super(context);
            init();
        }

        public ReplyDialog(@NonNull Context context, @StyleRes int themeResId, String cid, String nicName) {
            super(context, themeResId);
            this.cid = cid;
            this.nicName = nicName;
            init();

        }

        private void init() {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            View view = LayoutInflater.from(context).inflate(R.layout.et_reply_laout, null);
            setContentView(view);
            et_reply = view.findViewById(R.id.et_reply);
            tv_send = view.findViewById(R.id.tv_send);
            tv_send.setOnClickListener(this);
            et_reply.setText("回复 " + nicName + "：");
            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.END | Gravity.BOTTOM);
            lp.width = width;
            dialogWindow.setAttributes(lp);
        }

        @Override
        public void onClick(View view) {

            CharSequence msg1 = et_reply.getText().toString().trim();
            if (msg1 instanceof Spannable) {
                Spannable spanText = (Spannable) msg1;
                Selection.setSelection(spanText, msg1.length());
            }
            String msg = et_reply.getText().toString().trim();
            et_reply.setSelection(msg.length());
            if (spu.getUser() == null) {
                PageCtrl.start2LoginActivity((Activity) context);
            } else {
                if (msg == null) {
                    TUtils.toast("请输入内容");
                } else {

                    sendComment(msg, cid);
                }
            }
        }

        private void sendComment(String content, String cid) {

            Map<String, String> map = new HashMap<>();
            map.put("nid", nid);
            map.put("title", nid);
            map.put("uid", spu.getUser().getUid());
            map.put("type", type);
            map.put("content", content);
            map.put("cid", cid);
            map.put("json_url", "fsdfsdfsfs");//随便传一个
            map.put("siteid", InterfaceJsonfile.SITEID);
            Factory.provideHttpService()
                    .newsComment(ParamUtils.getRequestParam(map))
                    .onBackpressureBuffer()
                    .subscribeOn(Schedulers.io())
                    .filter(new Func1<ComResultEntity, Boolean>() {
                        @Override
                        public Boolean call(ComResultEntity entity) {
                            LogUtils.i("200-->" + entity.code);
                            if ("200".equals(entity.code)) {
                                LogUtils.i("200-->成功");
                                return true;
                            }
                            LogUtils.i("200失败");
                            return false;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<ComResultEntity>() {
                        @Override
                        public void call(ComResultEntity entity) {

                            if ("200".equals(entity.code)) {
                                TUtils.toast("评论成功");
                                et_reply.setText("");
                            } else {
                                TUtils.toast(entity.msg);
                            }
//                            setData();
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            TUtils.toast("评论失败");

                        }
                    });
        }

    }

    public SinglePicker ShowReport() {
        int ts = (int) context.getResources().getDimension(R.dimen.x32);
        int w = (int) context.getResources().getDimension(R.dimen.x84);
        ArrayList<String> list = new ArrayList<>();
        list.add("淫秽色情");
        list.add("营销广告");
        list.add("恶意攻击谩骂");
        list.add("其他");
//        String[] ss = (String[]) list.toArray();
        final SinglePicker<String> picker = new SinglePicker<>((Activity) context, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTitleText("举报理由");
        picker.setTopHeight(50);//顶部标题栏高度
        picker.setTopLineColor(context.getResources().getColor(R.color.color_dddddd));//顶部标题栏下划线颜色
        picker.setTopLineHeight(1);//顶部标题栏下划线高度
        picker.setTitleTextColor(context.getResources().getColor(R.color.color_333333));
        picker.setCancelTextColor(context.getResources().getColor(R.color.color_108ee9));//顶部取消按钮文字颜色
        picker.setCancelTextSize(14);
        picker.setSubmitTextColor(context.getResources().getColor(R.color.color_108ee9));//顶部确定按钮文字颜色
        picker.setSubmitTextSize(14);
        picker.setTitleTextSize(14);
        picker.setTextSize(14);
        picker.setSelectedIndex(1);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
//        picker.setLabel("分");
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(context.getResources().getColor(R.color.color_333333));//前四位值是透明度
        picker.setUnSelectedTextColor(context.getResources().getColor(R.color.color_a9a9a9));
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {

            }
        });

        return picker;
    }

    private void ReportUser(String uid, String content, String type) {

        Map<String, String> map = new HashMap<>();

        map.put("uid", uid);

//        map.put("content", content);
        map.put("optionsRadios", type);
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .reportUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity entity) {

                        if ("200".equals(entity.code)) {
                            TUtils.toast(entity.msg);

                        } else {
                            TUtils.toast(entity.msg);
                        }
//
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {


                    }
                });
    }

}
